using Microsoft.EntityFrameworkCore;

namespace EFCoreManyToManyDemo;

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {

    }

    public DbSet<Order> Orders { get; set; }
    public DbSet<Product> Products { get; set; }
    public DbSet<OrderItem> OrderItems { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Order>().ToTable("Orders").HasKey(o => o.Id);
        modelBuilder.Entity<Order>().Property(t => t.Id).ValueGeneratedOnAdd();
        modelBuilder.Entity<Order>()
            .HasMany(o => o.Products)
            .WithMany(Product.OrderName)
            .UsingEntity<OrderItem>(
                l => l.HasOne(t => t.Product).WithMany(Product.OrderItemName).HasForeignKey(e => e.ProductId),
                r => r.HasOne(t => t.Order).WithMany().HasForeignKey(e => e.OrderId));

        modelBuilder.Entity<Product>().ToTable("Products").HasKey(o => o.Id);
        modelBuilder.Entity<Product>().Property(t => t.Id).ValueGeneratedOnAdd();
        modelBuilder.Entity<Product>().OwnsOne(p => p.Category, sa =>
        {
            sa.WithOwner(d => d.Product);
            sa.Navigation(d => d.Product).UsePropertyAccessMode(PropertyAccessMode.Property);
            sa.Property(p => p.Type).HasColumnName("Type");
            sa.Ignore(p => p.Description);
        });

        modelBuilder.Entity<OrderItem>().ToTable("OrderItems").HasKey(o => o.Id);
        modelBuilder.Entity<OrderItem>().Property(t => t.Id).ValueGeneratedOnAdd();

        base.OnModelCreating(modelBuilder);
    }
}